<template>
  <!-- 攻城狮  工程师 -->
  <div class="cart">
    <div class="good-list" v-if="list.length > 0">
      <div class="goods" v-for="data in list" :key="data._id">
        <van-checkbox class="checkbox" v-model="data.checked"
          >复选框</van-checkbox
        >
        <img class="goods-img" :src="data.product.coverImg" alt="" />
        <div class="goods-info">
          <p>{{ data.product.name }}</p>
          <div class="box">
            <span>￥{{ data.product.price }}</span>
            <div class="box-q">
              <van-stepper
                v-model="data.quantity"
                theme="round"
                button-size="22"
                disable-input
              />
            </div>
            <div class="box-w">
              <van-button
                name="delete-o"
                v-show="data.checked"
                @click="del(data._id)"
                type="danger"
                size="small"
                text="删除"
              ></van-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-else>购物车空空如也</div>
    <!-- 全选 -->
    <van-submit-bar
      :price="sumPrice * 100"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox v-model="checked">全选</van-checkbox>
      <!-- <span></span> -->
      <van-icon name="delete-o" v-show="checked" @click="dels" />
    </van-submit-bar>
  </div>
</template>

<script>
import {
  reqCartlist,
  addtocart,
  reqDeleteCart,
  reqDeleteCarts,
  addshuju,
} from "../../api/cart";
export default {
  data() {
    return {
      list: [],
    };
  },
  // 计算属性
  // $set vue中添加动态属性
  computed: {
    checked: {
      // 用于设置全选全不选
      set(flag) {
        console.log(flag);
        this.list.map((item) => this.$set(item, "checked", flag));
      },
      get() {
        // 购物车的长度被删除完了，变成0了
        if (this.list.length == 0) {
          return false;
        } else {
          return (
            this.list.length === this.list.filter((item) => item.checked).length
          );
        }
      },
    },
    // 返回选中的项
    selectgoods() {
      let selectList = [];
      this.list.filter((item) => {
        if (item.checked) {
          selectList.push({
            price: item.product.price,
            quantity: item.quantity,
            product: item._id,
          });
        }
      });
      return selectList;
    },
    // 计算总价
    sumPrice() {
      // reduce来实现求和
      return this.list
        .filter((item) => {
          return item.checked;
        })
        .reduce(function (pre, cur) {
          return (pre += cur.product.price * cur.quantity);
        }, 0);
    },
  },
  watch: {},

  methods: {
    async initCart() {
      const result = await reqCartlist();
      // console.log(result);
      this.list = result;
    },
    // 添加减少购物车
    async updatePro(id, num = 1) {
      const result = await addtocart({
        product: id,
        quantity: num,
      });
      // console.log("121212", result);
      // 下面的操作一定要发生在添加或者删除成功之后的回调中
      // 客户端操作
      this.list.forEach((data) => {
        if (data.product._id == id) {
          data.quantity = data.quantity + num;
        }
      });
    },
    // 根据id删除单个购物车数据
    async del(id) {
      const result = await reqDeleteCart(id);
      console.log("删除", result);
      this.initCart();
    },
    // 批量删除
    async dels(id) {
      // ids数据从哪来？
      const result = await reqDeleteCarts(this.selectgoods);
      // const result = await reqDeleteCarts(id);
      console.log("全部删除",result);
      this.initCart();
    },
    // 提交订单
    async onSubmit() {
      const receiver = this.$store.state.address.receiver;
      const regions = this.$store.state.address.regions;
      const address = this.$store.state.address.addres;
      const tel = this.$store.state.address.tel;
      const orderDetails = this.selectgoods;
      if (receiver && regions && address && tel) {
        // 如果都存在才能生成订单order
        const res = await addshuju({
          receiver,
          regions,
          address,
          orderDetails,
        });
        this.$router.push("/order");
      } else {
        // 跳转到添加收货人地址页面
        this.$router.push("/address");
      }
    },
     //点击回去详情
    goback() {
      this.$router.go(-1);
    }
  },
  created() {
    this.initCart();
  },
  mounted() {},
  components: {},
};
</script>
<style scoped>
.good-list {
  padding-bottom: 50px;
}
.goods {
  display: flex;
  height: 100px;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 15px;
}
.checkbox {
  width: 20px;
  height: 20px;
}
.goods-img {
  width: 80px;
  height: 80px;
}
.goods-info {
  flex: 1;
  padding-left: 10px;
}
.van-submit-bar {
  bottom: 50px;
}
.box-q {
  margin-right: 50px;
}
.box {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.box-w {
  width: 50px;
}
</style>
